﻿Friend Class ScanFolder
    Public Shared Sub ScanShareForChanges(ByVal share As Entities.SharedWatchFolder, ByVal startPath As String)
        Manager.OnLogEvent(String.Format("Scan of changes for share ""{0}"" starting in folder ""{1}"" started...", share.Name, startPath))

        Dim clsTracker As New ScanTracker
        clsTracker.CurrentPath = startPath
        clsTracker.Share = share
        clsTracker.Recursive = share.Recursive

        Select Case share.GroupMode
            Case Entities.GroupMode.GroupSubDirectories
                ScanFolder_GroupSubDirectories.Scan(clsTracker)
            Case Entities.GroupMode.GroupIdenticalExtensionlessFilenames
                ScanFolder_GroupIndenticalFilenames.Scan(clsTracker)
            Case Entities.GroupMode.IndividualFiles
                ScanFolder_IndividualFiles.Scan(clsTracker)
        End Select

        'create missing mediainfo
        CreateOrUpdateMissingMediaInfo(clsTracker)

        'handle orphaned files
        HandleOrphanedFiles()

        Manager.OnLogEvent(String.Format("Scan of changes for share ""{0}"" starting in folder ""{1}"" completed", share.Name, startPath))
    End Sub

    Private Shared Sub HandleOrphanedFiles()
        Using t As New DataStore.TransactionScope
            DataStore.SharedItemsFiles.ReevalOrphanedSince(t)

            DataStore.SharedItemsFiles.RemoveOldOrphans(Now.Subtract(TimeSpan.FromDays(180)), t)
            t.Complete()
        End Using
    End Sub

    Private Shared Sub CreateOrUpdateMissingMediaInfo(ByVal tracker As ScanTracker)
        'check and make sure that there are no movies without a current movieinfo
        Dim aItems As Generic.List(Of Entities.SharedItem) = DataStore.SharedItems.GetAllMoviesWithMissingOrOutdatedMediaInfo
        For Each clsItem As Entities.SharedItem In aItems
            Dim clsMI As Entities.MediaInfo
            clsMI = ScanFolder_Common.CreateMediaInfoEx(clsItem)
            If clsMI IsNot Nothing Then
                Using t As New DataStore.TransactionScope
                    DataStore.MediaInfo.Save(clsMI, t)
                    clsItem.HasMediaInfo = True
                    DataStore.SharedItems.Save(clsItem, t)
                    t.Complete()
                End Using
                Manager.OnSharedItemUpdated(clsItem)
            End If
        Next
    End Sub

End Class

